<!-- 应用预览 -->
<template>
    <div v-loading="loading" class="app-preview-wrap">
        <template v-if="!loading">
            <div v-if="isHasFeature('native_preview')" class="left-wrap">
                <div class="left-header">快速导航</div>
                <el-scrollbar height="100%">
                    <el-menu
                        :default-active="currentPageId"
                        class="page-menu"
                    >
                        <!-- 自定义页面组 -->
                        <template v-for="(item, index) in customPageData" :key="index">
                            <el-sub-menu :index="`customPage${index}`">
                                <template #title>
                                    <div class="page-sub-menu-title">
                                        <el-icon class="page-sub-menu__icon-arrow"><icon-arrow-down /></el-icon>
                                        <el-icon><icon-folder /></el-icon>
                                        <div :title="item.group" class="title-warp">
                                            {{ item.group }}
                                        </div>
                                        <div class="actions-warp"></div>
                                    </div>
                                </template>
                                <template v-for="(pageItem, pageIndex) in item.pages" :key="pageItem.router">
                                    <el-menu-item :index="pageItem.router" @click="onSelectPage(pageItem.router)">
                                        <div class="page-menu-item">
                                            <el-icon v-if="pageItem.router === homePageRouter" title="首页" class="title-tag"><icon-home /></el-icon>
                                            <div :title="pageItem.name" class="title-warp">
                                                {{ pageItem.name }}
                                            </div>
                                            <div class="actions-warp"></div>
                                        </div>
                                    </el-menu-item>
                                </template>
                            </el-sub-menu>
                        </template>
                    </el-menu>
                </el-scrollbar>
            </div>

            <div class="main-wrap">
                <!-- 如果iframe出现滚动条，是因为浏览器的安全设置禁止了在本地文件系统中运行的 JavaScript 访问 iframe 的内容，从而导致 CSS 样式也无法应用 -->
                <!-- 解决此问题的一种方法是将 HTML 文件放在 Web 服务器上，然后通过使用 Web 服务器的 URL 来访问该文件 -->
                <iframe
                    v-if="!loading"
                    ref="iframeEl"
                    :src="previewUrl"
                    frameborder="0"
                    seamless=""
                    allowtransparency="true"
                    class="preview-iframe"
                    @load="onIframeLoad"
                />
            </div>

            <div class="right-wrap">
                <div class="right-header">
                    {{ appName || '未命名应用' }}
                </div>
                <div class="right-content">
                    <div class="code-wrap">
                        <qrcode-vue :value="previewUrl" :size="160" level="H" class="code-image" />
                        <div class="code-tip-txt">扫描二维码预览，手机预览</div>
                    </div>
                    <el-input :modelValue="previewUrl" class="code-input">
                        <template #append>
                            <clipboard-button :content="previewUrl" class="copy-code-btn">复制</clipboard-button>
                        </template>
                    </el-input>
                </div>
            </div>
        </template>
    </div>
</template>

<script>
import { defineComponent, toRefs, ref, computed } from 'vue'
import { useEditStore } from '@/store'
import { ElMessage, ElNotification } from 'element-plus'
import QrcodeVue from 'qrcode.vue'
import { getApp, getAppAliyun } from '@/api/app'
import { previewOriginURL } from '@/config'
import useFeature from '@/libs/feature'
import ClipboardButton from '@/components/clipboard-button'
import useH5DataFormat from './hooks/h5-data-format'
export default defineComponent({
    name: 'AppPreview',
    components: {
        QrcodeVue,
        ClipboardButton
    },
    props: {
        appId: {
            type: String,
            default: ''
        },
        historyId: {
            type: String,
            default: ''
        },
        pageId: {
            type: String,
            default: ''
        }
    },
    setup(props) {
        const { appId, historyId, pageId } = toRefs(props)

        const editStore = useEditStore()

        const currentPageId = ref(pageId.value)
        const currentHistoryId = ref(historyId.value)
        const loading = ref(true)
        const appData = ref({})
        const appName = ref('')
        const cataData = ref([])

        const iframeEl = ref(null)

        const {
            isHasFeature
        } = useFeature()

        const {
            appDatas,
            tabbarData
        } = useH5DataFormat()

        // 首页路由名称
        const homePageRouter = computed(() => appData.value?.data?.['homepage-router'] || '')

        // 自定义页面列表
        const customPageData = computed(() => cataData.value.data)

        // 预览地址
        const previewUrl = computed(() => `${previewOriginURL}?pageRouter=${currentPageId.value}&appId=${appId.value}&historyId=${currentHistoryId.value}`)

        if (appId.value) {
            loading.value = true
            getAppData().finally(() => {
                loading.value = false
            })
        } else {
            ElNotification({
                title: '提示',
                message: 'appId为空，获取应用数据失败',
                type: 'warning',
                duration: 0,
                showClose: false
            })
        }

        function onIframeLoad() {
            // todo 模拟数据用的，上线时可删除/注释
            iframeEl.value?.contentWindow.postMessage({
                appDatas: appDatas.value,
                tabbarData: tabbarData.value
            }, '*')
            // todo end
        }

        // 获取app数据
        function getAppData() {
            return new Promise(async (resolve, reject) => {
                const resApp = await getApp({
                    appId: appId.value,
                    historyId: historyId.value
                })
                if (resApp.Status === 1) {
                    const { OssGetUrl, HistoryId, Name } = resApp.Data
                    currentHistoryId.value = HistoryId
                    appName.value = Name
                    const resAppData = await getAppAliyun(OssGetUrl)
                    if (resAppData.data) {
                        // const dataJson = resAppData?.data?.DataJson || {} // 上线时用这行
                        const dataJson = editStore // todo 上线时删除
                        appData.value = dataJson.appData
                        cataData.value = dataJson.cataData
                        if (!pageId.value) {
                            currentPageId.value = dataJson.appData?.data?.['homepage-router'] || ''
                        }
                        resolve(resAppData)
                    } else {
                        ElMessage.error('app数据不存在')
                    }
                } else {
                    ElMessage.error(resApp.Message || '网络错误')
                    reject()
                }
            })
        }

        // 选中页面
        const onSelectPage = router => {
            currentPageId.value = router
        }

        return {
            isHasFeature,

            currentPageId,
            loading,
            appName,
            homePageRouter,

            customPageData,

            previewUrl,

            iframeEl,

            onIframeLoad,
            onSelectPage
        }
    }
})
</script>

<style lang="less" scoped>
@import './app-preview.less';
</style>